package xcmg.device.web.company;

import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import xcmg.device.dao.entity.company.CompanyDealerDO;
import xcmg.device.dao.entity.company.EmployeeSettingDO;
import xcmg.device.infra.AuthCode;
import xcmg.device.infra.BasicController;
import xcmg.device.infra.ErrorCode;
import xcmg.device.infra.StringUtil;
import xcmg.device.service.company.EmployeeService;
import xcmg.device.service.company.EmployeeSettingService;
import xcmg.device.service.vo.agent.ServiceBasicDataAgentVO;
import xcmg.device.service.vo.company.EmployeeSettingResultVO;
import xcmg.device.service.vo.company.EmployeeSettingVO;
import yb.ecp.fast.infra.annotation.FastMappingInfo;
import yb.ecp.fast.infra.infra.ActionResult;
import yb.ecp.fast.infra.infra.SearchCommonVO;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * EmployeeSetting Controller 实现类
 */
@RestController
@RequestMapping("/employeeSetting")
public class EmployeeSettingController extends BasicController {
    private static final Logger logger = LoggerFactory.getLogger(EmployeeSettingController.class);
    @Autowired
    private EmployeeSettingService employeeSettingService;

    @Autowired
    private EmployeeService employeeService;

    @Value("${device.impSize.EmployeeSettingMaxImpSize:10000}")
    private Integer maxImpSize;

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ApiOperation(value = "供应商职工岗位配置信息表-保存")
    @FastMappingInfo(needLogin = true, code = AuthCode.Employee.SAVE_SETTING)
    public ActionResult<String> save(@RequestBody EmployeeSettingVO employeeSettingVO) {
        if (null == employeeSettingVO || StringUtil.isEmpty(employeeSettingVO.getJobId())
                || StringUtil.isEmpty(employeeSettingVO.getOrgId())
                || null == employeeSettingVO.getNumberEmp()
        ) {
            return actionResult(ErrorCode.IllegalArument);
        }
        try {
            ErrorCode code = employeeSettingService.save(employeeSettingVO, getUserId(), getUserName(), getOrgId());
            return actionResult(code);
        } catch (Exception e) {
            return new ActionResult(ErrorCode.Failure.getCode(), e.getMessage());
        }
    }

    @RequestMapping(value = "/configList", method = RequestMethod.POST)
    @ApiOperation(value = "主机厂查询供应商职工岗位配置")
    @FastMappingInfo(needLogin = true)
    public ActionResult<EmployeeSettingResultVO> configListByPage(@RequestBody SearchCommonVO<EmployeeSettingVO> condition) throws Exception {
        if (null == condition.getFilters()) {
            condition.setFilters(new EmployeeSettingVO());
        }
        condition.getFilters().setOrgId(getOrgId());
        EmployeeSettingResultVO vo = employeeSettingService.list(condition, false);
        return actionValueResult(vo);
    }

    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ApiOperation(value = "主机厂查询供应商职工岗位配置-含有配置信息")
    @FastMappingInfo(needLogin = true)
    public ActionResult<EmployeeSettingResultVO> listByPage(@RequestBody SearchCommonVO<EmployeeSettingVO> condition) throws Exception {
        if (null == condition.getFilters()) {
            condition.setFilters(new EmployeeSettingVO());
        }
        condition.getFilters().setOrgId(getOrgId());
        EmployeeSettingResultVO vo = employeeSettingService.list(condition, true);
        return actionValueResult(vo);
    }

    @RequestMapping(value = "/export" , method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    @ApiOperation(value = "导出")
    public void export() throws Exception {
        employeeSettingService.export(getOrgId());
    }


    @RequestMapping(value = "/exportRpt" , method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true, code = AuthCode.Employee.EXP_SETTING)
    @ApiOperation(value = "导出")
    public void exportRpt() throws Exception {
        employeeSettingService.exportRpt(getOrgId());
    }



    @ResponseBody
    @RequestMapping(value = "/import", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true, code = AuthCode.Employee.IMP_SETTING)
    public ActionResult<String> importExcel(MultipartHttpServletRequest multipartHttpServletRequest) throws Exception {
        MultipartFile multipartFile = multipartHttpServletRequest.getFile(multipartHttpServletRequest.getFileNames().next());
        if (multipartFile == null || multipartFile.isEmpty()) {
            logger.error("ExcelFileUtil:read 上传的文件无效!");
            return new ActionResult(ErrorCode.ImportExcelEndWithXLS.getCode(), "上传的文件无效");
        }
        try {
            String orgId = getOrgId();
            String userName = getUserName();
            Map<String, CompanyDealerDO> companyDealerDOMap = employeeSettingService.queryAllCompanyDealerDOKeyByNameList(orgId);
            Map<String, ServiceBasicDataAgentVO> jobMap = employeeService.queryJobListByMap(orgId);
            List<EmployeeSettingDO> excelDatas = getExcelDoDatas(multipartFile, orgId, jobMap, companyDealerDOMap, userName);
            employeeSettingService.batchSave(excelDatas);
            return actionResult(ErrorCode.Success);
        } catch (Exception e) {
            logger.error("",e);
            return actionResult(ErrorCode.Failure, e.getMessage());
        }
    }

    private List<EmployeeSettingDO> getExcelDoDatas(MultipartFile multipartFile, String orgId, Map<String, ServiceBasicDataAgentVO> jobMap, Map<String, CompanyDealerDO> companyDealerDOMap, String userName) throws IOException {
        Workbook workbook;
        InputStream inputStream;
        inputStream = multipartFile.getInputStream();
        String fileName = multipartFile.getOriginalFilename();
        if (fileName.endsWith(".xls")) {
            workbook = new HSSFWorkbook(inputStream);
        } else if (fileName.endsWith(".xlsx")) {
            workbook = new XSSFWorkbook(inputStream);
        } else {
            logger.info("ExcelFileUtil:read 上传文件的类型错误!");
            throw new RuntimeException("上传文件的类型错误!");
        }
        Sheet sheet = workbook.getSheetAt(0);
        int totalRow = sheet.getLastRowNum();
        if (totalRow < 2) {
            throw new RuntimeException("导入模板不正确");
        }
        Row titleRow = sheet.getRow(1);
        int totalCell = titleRow.getLastCellNum();
        if (totalCell < 2 || null == titleRow.getCell(0)) {
            throw new RuntimeException("导入模板不正确");
        }
        if (!"代理商".equals(titleRow.getCell(1).toString().trim())) {
            throw new RuntimeException("导入模板不正确, 请使用导出文件做模板导入");
        }
        List<ServiceBasicDataAgentVO> jobIds = new ArrayList<>();
        List<EmployeeSettingDO> result = new ArrayList<>();
        for (int i = 2; i < totalCell; i++) {
            Cell cell = titleRow.getCell(i);
            if (null == cell || StringUtils.isBlank(cell.toString().trim())) {
                throw new RuntimeException("导入模板不正确,表头有非法信息");
            }
            ServiceBasicDataAgentVO jobId = jobMap.get(cell.toString().trim());
            if (null == jobId) {
                throw new RuntimeException("导入模板不正确,表头中" + cell.toString() + "为非法信息");
            }
            jobIds.add(jobId);
        }
        Date now = new Date();
        for (int i = 2; i <= totalRow; i++) {
            Row curRow = sheet.getRow(i);
            if (curRow == null || null == curRow.getCell(1) || StringUtils.isBlank(curRow.getCell(1).toString())) {
                continue;
            }
            CompanyDealerDO companyDealerDO = companyDealerDOMap.get(curRow.getCell(1).toString());
            if (null == companyDealerDO) {
                throw new RuntimeException("代理商“" + curRow.getCell(1) + "”不存在");
            }
            for (int k = 0; k < jobIds.size(); k++) {
                EmployeeSettingDO detailDo = new EmployeeSettingDO();
                Cell cell = curRow.getCell(k + 2);
                try {
                    cell.setCellType(CellType.STRING);
                    detailDo.setNumberEmp(Integer.parseInt(cell.toString()));
                } catch (Exception e) {
                    logger.warn("", e);
                    detailDo.setNumberEmp(0);
                }
                detailDo.setCreateDate(now);
                detailDo.setCreateName(userName);
                detailDo.setUpdateName(userName);
                detailDo.setUpdateDate(now);
                detailDo.setOrgId(companyDealerDO.getPlatOrgId());
                detailDo.setOrgName(companyDealerDO.getCompanyName());
                detailDo.setFactoryOrgId(orgId);
                detailDo.setJobId(jobIds.get(k).getId());
                detailDo.setJob(jobIds.get(k).getName());
                result.add(detailDo);
            }
        }
        return result;
    }

}
